package com.tma.timesheettracker.activity;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.tma.timesheettracker.R;
import com.tma.timesheettracker.adapter.AutoCompleteAdapter;
import com.tma.timesheettracker.contentprovider.TimeTrackerContentProvider;
import com.tma.timesheettracker.model.ListTrackingEntry;
import com.tma.timesheettracker.model.Task;
import com.tma.timesheettracker.model.TrackingEntry;
import com.tma.timesheettracker.util.Util;

public class RecordWorkActivity extends Activity implements
		OnSeekBarChangeListener, OnClickListener {

	public static final int REQUEST_CODE = 3333;
	private SeekBar m_durationSeek;
	private Button m_daylog;
	private TextView m_durationValue;
	private ContentResolver m_resolver;
	private AutoCompleteTextView m_autoTask;
	private List<Task> m_lstTask = new ArrayList<Task>();
	private TrackingEntry m_entry = new TrackingEntry();
	private List<TrackingEntry> m_lstEntry = new ArrayList<TrackingEntry>();
	private Task m_task;
	private boolean m_iscreate = false;
	private boolean m_isdulicateTaskName = false;
	private Bundle m_bundle;
	private String m_action = "";
	private String m_dayofRecord = "";

	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_recordwork);
		m_resolver = getContentResolver();
		getActionBar().setHomeButtonEnabled(true);
		m_autoTask = (AutoCompleteTextView) findViewById(R.id.autoTask);
		m_durationSeek = (SeekBar) findViewById(R.id.duration);
		m_durationSeek.setOnSeekBarChangeListener(this);
		m_daylog = (Button) findViewById(R.id.btnRecordToday);
		m_daylog.setOnClickListener(this);
		m_durationValue = (TextView) findViewById(R.id.durationValue);
		AutoCompleteAdapter adapter = new AutoCompleteAdapter(this, m_lstTask);
		m_autoTask.setAdapter(adapter.getAdapter());
		m_bundle = getIntent().getExtras();
		if (m_bundle != null) {
			m_action = m_bundle.getString(Util.ACTION);
			m_lstEntry = (List<TrackingEntry>) m_bundle
					.getSerializable(Util.TIME_SHEET_TRACKING);
			m_dayofRecord = m_bundle.getString(Util.DAY_TO_RECORD);

			if (m_dayofRecord != null || !m_dayofRecord.equals("")) {
				try {
					m_daylog.setText(Util.getDateFormat(Util.DATE_FORMATTER
							.parse(m_dayofRecord)));
				} catch (ParseException e) {

				}
			}

			Log.v("bundle", m_dayofRecord);
		}

		if (m_action.equals(Util.EDIT)) {
			m_daylog.setEnabled(false);
			m_iscreate = false;
			setlimitSeekBarInEidtAction();
		} else if (m_action.equals(Util.CREATE)) {
			m_iscreate = true;
			setlimitseekbarInCreateAction();
		}
	}

	public void setlimitSeekBarInEidtAction() {
		int taskId = Integer.parseInt(m_bundle.getString("Task_Id"));
		m_task = TimeTrackerContentProvider.TaskTable.getTask(m_resolver,
				taskId);
		Log.i("Task_ID dafasdf", m_task.getId() + "");
		if (m_task.getName() != null) {
			m_autoTask.setText(m_task.getName());
		}
		if (m_lstEntry != null) {
			ListTrackingEntry lstTracking = new ListTrackingEntry(m_lstEntry,
					true, taskId);
			m_entry = lstTracking.getM_entry();
			m_durationSeek.setProgress(m_entry.getDuration());
			m_durationSeek.setMax(m_entry.getDuration()
					+ (Util.WORKING_HOURS - lstTracking.getM_duration()));
		}
	}

	public void setlimitseekbarInCreateAction() {
		if (m_lstEntry != null) {
			ListTrackingEntry lstTrakcing = new ListTrackingEntry(m_lstEntry,
					false, 0);
			m_durationSeek.setMax(Util.WORKING_HOURS
					- lstTrakcing.getM_duration());
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_recordtask, menu);
		return true;
	}

	private boolean isValid() {
		return (!m_autoTask.getText().toString().equals("") && m_durationSeek
				.getProgress() != 0) ? true : false;
	}

	private boolean LogNotFirstTime() {
		return (m_lstEntry.size() > 0) ? true : false;
	}

	private boolean changedTaskName() {
		return (!m_autoTask.getText().toString().equals(m_task.getName())) ? true
				: false;
	}

	private Task lookupTask() {
		return TimeTrackerContentProvider.TaskTable.getTask(m_resolver,
				m_autoTask.getText().toString().trim());
	}

	private TrackingEntry lookupEntry(int taskId) {
		return TimeTrackerContentProvider.TrackingEntryTable.getEntry(
				m_resolver, m_dayofRecord, taskId);
	}

	private boolean taskIsExist(Task task) {
		return task.getName() != null ? true : false;
	}

	private boolean taskLogged(TrackingEntry entry) {
		return (entry.getDate() != null) ? true : false;
	}

	private void insertEntry(int taskid) {
		try {
			TimeTrackerContentProvider.TrackingEntryTable.insertEntry(
					m_resolver, createEntry(taskid));
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	private void updateEntry(TrackingEntry existEntry, boolean istaskexist) {
		if (istaskexist) {
			existEntry.setDuration(m_durationSeek.getProgress()
					+ existEntry.getDuration());
		} else {
			existEntry.setDuration(m_durationSeek.getProgress());
		}
		TimeTrackerContentProvider.TrackingEntryTable.updateEntry(m_resolver,
				existEntry);
	}

	private void updateNewTaskforEntry(int taskID) {
		m_entry.setTask_id(taskID);
		m_entry.setDuration(m_durationSeek.getProgress());
		TimeTrackerContentProvider.TrackingEntryTable.updateEntry(m_resolver,
				m_entry);
	}

	private void deleteOldEntry() {
		TimeTrackerContentProvider.TrackingEntryTable.deleteEntry(m_resolver,
				m_entry.getId());
	}

	private int createTask() {
		Task newTask = new Task();
		newTask.setName(m_autoTask.getText().toString());
		Uri uri = m_resolver.insert(TimeTrackerContentProvider.TASK_URI,
				TimeTrackerContentProvider.TaskTable.toContentValues(newTask));
		int taskId = Integer.parseInt(uri.getLastPathSegment());
		return taskId;
	}

	private TrackingEntry createEntry(int taskid) throws ParseException {
		TrackingEntry newEntry = new TrackingEntry();
		newEntry.setUser_id(Util.DEFAULT_USER_ID);
		newEntry.setTask_id(taskid);
		newEntry.setDate(Util.dfm.parse(m_dayofRecord));
		Log.v("Date tim:", m_dayofRecord);
		newEntry.setDuration(m_durationSeek.getProgress());
		return newEntry;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			return true;
		case R.id.save:
			if (!m_iscreate) {
				if (isValid()) {
					if (changedTaskName()) {
						Task task = lookupTask();
						if (taskIsExist(task)) {
							TrackingEntry existEntry = lookupEntry(task.getId());
							if (taskLogged(existEntry)) {
								updateEntry(existEntry, true);
								deleteOldEntry();
							} else {
								updateNewTaskforEntry(task.getId());
							}
						} else {
							int taskId = createTask();
							updateNewTaskforEntry(taskId);
						}
					} else {
						updateEntry(m_entry, false);
					}
					Intent intent = new Intent(RecordWorkActivity.this,
							MainActivity.class);
					startActivity(intent);
					finishActivity();
				} else {
					Toast.makeText(this, Util.WARNING_TASK_LOGGING,
							Toast.LENGTH_LONG).show();
				}
			} else if (m_iscreate) {
				if (isValid()) {
					Task task = lookupTask();
					if (taskIsExist(task)) {
						if (LogNotFirstTime()) {
							for (TrackingEntry entry : m_lstEntry) {
								if (entry.getTask_id() == task.getId()) {
									updateEntry(entry, true);
									m_isdulicateTaskName = true;
									break;
								}
							}
							if (!m_isdulicateTaskName) {
								insertEntry(task.getId());
							}
						} else {
							insertEntry(task.getId());
						}
					} else {
						int taskId = createTask();
						insertEntry(taskId);
					}
					Intent intent = new Intent(RecordWorkActivity.this,
							MainActivity.class);
					startActivity(intent);
					finishActivity();
				} else {
					Toast.makeText(this, Util.WARNING_TASK_LOGGING,
							Toast.LENGTH_LONG).show();
				}
			}
			;
			return true;
		case R.id.delete:
			if (!m_iscreate) {
				List<TrackingEntry> lstEntry = null;

				lstEntry = TimeTrackerContentProvider.TrackingEntryTable
						.getEntries(m_resolver, m_dayofRecord);

				if (lstEntry.size() == 1) {
					m_entry.setDuration(0);
					TimeTrackerContentProvider.TrackingEntryTable.updateEntry(
							m_resolver, m_entry);
				} else {
					int deleterows = TimeTrackerContentProvider.TrackingEntryTable
							.deleteEntry(m_resolver, m_entry.getId());
					Log.v("Nr of deleted rows:", deleterows + "");
				}
				Intent intent = new Intent(RecordWorkActivity.this,
						MainActivity.class);
				startActivity(intent);
				finishActivity();
			}
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void onClick(View v) {
		String[] day = Util.getYearMonthDay(m_dayofRecord);
		if (v == m_daylog) {
			DatePickerDialog datedialog = new DatePickerDialog(
					this,
					new OnDateSetListener() {

						public void onDateSet(DatePicker view, int year,
								int monthOfYear, int dayOfMonth) {
							try {
								m_dayofRecord = Util.formatDate(year,
										monthOfYear, dayOfMonth);
								m_daylog.setText(Util
										.getDateFormat(Util.DATE_FORMATTER
												.parse(m_dayofRecord)));
							} catch (ParseException e) {
								e.printStackTrace();
							}

							m_lstEntry = TimeTrackerContentProvider.TrackingEntryTable
									.getEntries(m_resolver, m_dayofRecord);

							if (m_iscreate) {
								setlimitseekbarInCreateAction();
							} else {
								setlimitSeekBarInEidtAction();
							}
						}
					}, Integer.parseInt(day[0]), Integer.parseInt(day[1]) - 1,
					Integer.parseInt(day[2]));
			datedialog.show();
		}
	}

	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		m_durationValue.setText(progress + "");
	}

	public void onStartTrackingTouch(SeekBar seekBar) {

	}

	public void onStopTrackingTouch(SeekBar seekBar) {

	}

	private void finishActivity() {
		setResult(Util.ACTION_CLOSE);
		finishActivity(REQUEST_CODE);
		finish();
	}

}
